package com.taxsearch.controller;

import com.taxsearch.util.roomutil.PropertyUtil;

import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * 
 * @Title:DBUtil
 * @Description: 连接数据库工具类
 * @author 高敏
 * @version V1.0
 * @date 2018年8月16日
 */
public class DBUtil {
	private static Connection connection = null;
	private static PreparedStatement smt = null;
	private static ResultSet rs = null;
	
	//链接数据库
	public static Connection getConnection() {
		String USERNAMR = PropertyUtil.getProperty("jdbc_username").trim();
		String PASSWORD = PropertyUtil.getProperty("jdbc_password").trim();
		String DRVIER = PropertyUtil.getProperty("jdbc_driverClassName").trim();
		String URL = PropertyUtil.getProperty("jdbc_url").trim();
		//String URL = "jdbc:oracle:thin:@192.168.88.160:1521:CDFGSDB";
		try {
			Class.forName(DRVIER);
			connection = DriverManager.getConnection(URL, USERNAMR, PASSWORD);
			System.out.println("成功连接数据库");
		} catch (ClassNotFoundException e) {
			System.out.println("ClassNotFound");
		} catch (SQLException e) {
			System.out.println("连接分发库失败");
		}
		return connection;

	}
	
	//关闭连接
	public static void close(Connection connectionTemp){
//		if (rs != null) {
//            try {
//                rs.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//        if (smt != null) {
//            try {
//                smt.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
        if (connectionTemp != null) {
            try {
            	connectionTemp.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
		
	}
	
	//获得Blob类型的二进制图片
	public static byte[] getByteBlob(Connection connection,String RECORDSNO) throws IOException {
		try {
    		String sql=
    				"select DJ_UPZHAOPIAN from CGUESTERSP "
    				+"where RECORDSNO = '"+RECORDSNO+"'";
        	smt=connection.prepareStatement(sql);
			rs=smt.executeQuery();
			byte[] b = null;
			if(rs.next()){	
				Blob bb = rs.getBlob("DJ_UPZHAOPIAN");
				if(bb!=null) {                  
                    b = bb.getBytes(1, (int)bb.length());
                }
            }
			close(connection);
			return b;
		 } catch (SQLException e) {  
	            e.printStackTrace();  
	     } 
		close(connection);
		return null;
	}
}
